package com.my.chapter11;

import java.util.*;

public class practice32 {
    public static void main(String[] args) {
        NonCollectionSequence ns = new NonCollectionSequence();
        for(Pets p:ns.reversed()){
            System.out.print(p.id + "：" + p + ";  ");
        }
        System.out.println("");
        for(Pets p:ns.randomized()){
            System.out.print(p.id + "：" + p + ";  ");
        }
        System.out.println("");
        Iterator<Pets> it = ns.iterator();
        while(it.hasNext()){
            Pets p = it.next();
            System.out.print(p.id + "：" + p + ";  ");
        }
        System.out.println("");
    }
}

class NonCollectionSequence{
    protected Pets[] pets = Pets.createArray(8);

    public Iterator<Pets> iterator(){
        return new Iterator<Pets>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index<pets.length;
            }

            @Override
            public Pets next() {
                return pets[index++];
            }
        };
    }

    public Iterable<Pets> reversed(){
        return new Iterable<Pets>(){
            @Override
            public Iterator<Pets> iterator() {
                return new Iterator<Pets>() {
                    int current = pets.length-1;

                    @Override
                    public boolean hasNext() {
                        return current>-1;
                    }

                    @Override
                    public Pets next() {
                        return pets[current--];
                    }
                };
            }

        };
    }

    public Iterable<Pets> randomized(){
        return new Iterable<Pets>() {
            @Override
            public Iterator<Pets> iterator() {
                List<Pets> shuffled = new ArrayList<Pets>(Arrays.asList(pets));
                Collections.shuffle(shuffled,new Random(47));
                return shuffled.iterator();
            }
        };
    }
}

